<template>
  <div class="role-page">
    <div class="table-field">
      <div class="btns-fun-field">
        <el-button  type="primary" @click.prevent="showAddEditDialog"  :icon="Plus">
          新增权限
        </el-button>
    </div>
      <el-table
        :data="tableData"
        border
        :max-height="710"
        stripe
        style="width: 100%"
        v-loading="tableLoading"
        default-expand-all
        row-key="id"
      >
        <el-table-column prop="name" label="权限名" width="230" />
        <el-table-column prop="code" label="权限code" width="240" />
        <el-table-column prop="createTime" label="创建时间" width="200" />
        <el-table-column label="操作" min-width="220px">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click.prevent="showAddEditDialog(scope.row, 1)"
              >增加子权限</el-button
            >
            <el-button
              type="danger"
              size="small"
              @click.prevent="showRemoveDialog(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-field" >
        <el-pagination
          v-model:current-page="formData.pageIndex"
          v-model:page-size="formData.pageSize"
          :page-sizes="[10, 20, 30, 40]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="formData.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <el-dialog
      v-if="addDialogVisible"
      v-model="addDialogVisible"
      :title="addEditForm.title"
      width="550px"
    >
      <div style="padding-right: 50px">
        <el-form
          :model="addEditForm"
          :rules="addEditRules"
          ref="addEditRef"
          :label-width="80"
        >
        <el-form-item label="父权限名"   prop="parentName" v-if="curPermissionType!=0">
            <el-input
              v-model="addEditForm.parentName"
              autocomplete="off"
              placeholder="请输入父权限名"
              :readonly="addEditForm.parentNameDisabled"
            />
          </el-form-item>
          <el-form-item label="权限名" prop="name">
            <el-input
              v-model="addEditForm.name"
              autocomplete="off"
              placeholder="请输入权限名"
              :disabled="addEditForm.disabled"
            />
          </el-form-item>
          <el-form-item label="权限code" prop="code">
            <el-input
              v-model="addEditForm.code"
              autocomplete="off"
              placeholder="请输入权限code(唯一值)"
              :disabled="addEditForm.disabled"
            />
          </el-form-item>  
          <el-form-item label="类型" prop="code">
            <el-select style="width: 100%;" v-model="addEditForm.type" placeholder="选择权限类型">
            <el-option
              v-for="option in usePermissionTypeList"
              :key="option.id"
              :label="option.name"
              :value="option.id"
            />
          </el-select>
          </el-form-item>
          <el-form-item label="可见性" prop="code" v-if="addEditForm.type=='2'">
            <el-select style="width: 100%;" v-model="addEditForm.visibility" placeholder="选择菜单项可见性">
            <el-option
              v-for="option in visibleTypeList"
              :key="option.id"
              :label="option.name"
              :value="option.id"
            />
          </el-select>
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input-number 
              :min="0"
              :max="99"
              v-model="addEditForm.sort"
              placeholder="请输入排序号"
            />
          </el-form-item>  
        
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="startAddRole"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-if="removeDialogVisible"
      v-model="removeDialogVisible"
      title="删除权限"
      width="400px"
    >
      <span>确定要删除当前权限？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="removeDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="startRemoveRole"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from "vue";
import {
  getPermissionPagiation,
  addPermission,
  removePermission
  // addRole,
  // updateRole,
  // removeRole,
  // getPermissionTree,
} from "@/api/user-manage.api";
import { Plus } from "@element-plus/icons-vue";
import {  FormInstance, ElMessage } from "element-plus";
const formData = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
});


const permissionTypeList = [
  {
    id: 1,
    name: "菜单目录"
  },
  {
    id: 2,
    name: "菜单项"
  },
  {
    id: 3,
    name: "按钮"
  }
]
const visibleTypeList = [
  {
    id: 1,
    name: "显示在左侧菜单栏"
  },
  {
    id: 0,
    name: "不显示在左侧菜单栏"
  }
]
const curPermissionType = ref(0)
const usePermissionTypeList = computed(()=>{
  if( !curPermissionType.value ){
    return permissionTypeList
  }

  return permissionTypeList.filter(item=>{
    return item.id > curPermissionType.value;
  })

})



const removeDialogVisible = ref(false);
const addDialogVisible = ref(false);
const addEditRef = ref<FormInstance>();
const addEditForm = reactive({
  id: null,
  name: "",
  code: '',
  type: '',
  level: 0,
  sort: 0,
  visibility: 1,
  parentName: "",
  parentId: 0,
  disabled: false,
  parentNameDisabled: false,
  title: "",
  permissionIdList: [],
});
const addEditRules = reactive({
  name: [
    { required: true, message: "请输入权限名", trigger: "blur" },
    { min: 1, max: 30, message: "长度为1~30位", trigger: "blur" },
  ],
});



const showAddEditDialog = (item: any, type: number) => {
  //新增权限
  if (item.target) {
    curPermissionType.value = 0;
    addEditForm.title = "新增权限";
    addEditForm.id = null;
    addEditForm.name = "";
    addEditForm.code = "";
    addEditForm.type = "";
    addEditForm.level = 0;
    addEditForm.sort = 0;
    addEditForm.visibility = 1;
    addEditForm.parentId = 0;
    addEditForm.parentName = "";
    addEditForm.disabled = false;
    addEditForm.parentNameDisabled = false;
    addDialogVisible.value = true;
    return;
  }

  //增加子项权限
  if (type === 1) {
    addEditForm.title = "新增子权限";
    curPermissionType.value = item.type;
    addEditForm.parentName = item.name;
    addEditForm.parentId = item.id;
    addEditForm.name = "";
    addEditForm.code = "";
    addEditForm.type = "";
    addEditForm.visibility = 1;
    addEditForm.sort = 0;
    addEditForm.level = item.level+1;
    addEditForm.parentNameDisabled = true;
    addDialogVisible.value = true;
    return;
  }

};

const tableLoading = ref(false);
const tableData = ref([]);

const curSelectRow = ref({ id: '' });
const showRemoveDialog = (item: any) => {
  removeDialogVisible.value = true;
  curSelectRow.value = item;
  console.log("item: ", item);
};

const startRemoveRole = () => {

  let idList:Array<number|string> = [curSelectRow.value.id];
  removePermission(idList)
    .then((res) => {
      console.log("success~~~~~",res);
      removeDialogVisible.value = false;
      ElMessage({
        message: "权限删除成功",
        type: "success",
      });
      getDataList();
    })
    .catch((err) => {
      removeDialogVisible.value = false;
      ElMessage({
         message: err.msg || err || "网络错误",
        type: "error",
      });
    });
};

const startAddRole = () => {
  console.log("...")
  let formData = {
    name: addEditForm.name,
    code: addEditForm.code,
    type: addEditForm.type,
    parentId: addEditForm.parentId,
    parentName: addEditForm.parentName,
    level: addEditForm.level,
    visibility: addEditForm.visibility,
    sort: addEditForm.sort
  }

  addPermission( formData ).then( res=>{
    ElMessage({
      type: "success",
      message: "新增权限成功"
    })
    getDataList();
    addDialogVisible.value = false;
    console.log(res)
  }).catch( err=>{
      ElMessage({
        type: "error",
        message:  err.msg || err || "网络错误"
      })
    }
   );
};

const handleSizeChange = (value: number) => {
  console.log("handleSizeChange...", value);
  formData.pageSize = value;
  getDataList();
};

const handleCurrentChange = (value: number) => {
  console.log("handleCurrentChange...", value);
  formData.pageIndex = value;
  getDataList();
};

const getDataList = () => {
  tableLoading.value = true;
  getPermissionPagiation({
    pageSize: formData.pageSize,
    pageIndex: formData.pageIndex,
  })
    .then(function (res: any) {
      
      tableLoading.value = false;
      console.log(".......................");
      console.log(res);
      console.log(".......................");
      tableData.value = res.list || [];
      formData.total = Number(res.total);
    })
    .catch((error) => {
      console.log(error);
      tableLoading.value = false;
    });
};

const permissionList = ref([]);
const flatPermissionList = ref([]);
const checkedKeys = ref<any>([]);

const treeSelect = (item: any, curStatus: boolean) => {
  //如果是选中，则查询其父节点是否选中，如果没有选中，则把父节点也选中。
  if (curStatus) {
    let checkKeyList = checkedKeys.value;
    let parentIdList = checkParentNode(item);
    checkedKeys.value = [
      ...new Set([item.id, ...parentIdList, ...checkKeyList]),
    ];
  } else {
    checkedKeys.value = checkedKeys.value.filter((row) => row != item.id);
  }
};

const checkParentNode = (item: any): Array<any> => {
  let list = [];
  let flatNodeList = flatPermissionList.value;
  let findRes = flatNodeList.find((row) => row.id == item.parentId);
  if (findRes) {
    list.push(findRes.id);
    if (findRes.parentId) {
      let subList = checkParentNode(findRes);
      list.push(...subList);
    }
  }
  return list;
};

const flatTree = (treeData: any) => {
  return treeData.reduce((first: any, last: any) => {
    first.push(last);
    if (last.children && last.children.length) {
      first.push(...flatTree(last.children));
    }
    return first;
  }, []);
};

const startGetPermissionTree = () => {
  console.log("/...")
  // getPermissionTree({}).then(function (res: any) {
  //   permissionList.value = res;
  //   flatPermissionList.value = flatTree(res);
  //   console.log("flatPermissionList ", flatPermissionList.value);
  // });
};

onMounted(() => {
  getDataList();
  startGetPermissionTree();
});
</script>
<style lang="scss" scoped>
@import './PermissionList.scss'
</style>
